require 'rubygems'
require "rexml/document"
require "open-uri"
require "cgi"
require 'digest/md5'
require 'date'

#GLOBALS
CONSUMER_KEY = "FaaKedNASyBQIPujuGtOA"
CONSUMER_SECRET = "VtHRdaHt0otdmwyN6KMprjpGvKzoUReVZtEEhSy0"
ACCESS_KEY = '202832729-aDvW0BoCBjtQ1Ovqg9SMX5wbbaF6Ie6Nn9waugZM'
ACCESS_KEY_SECRET = 'nzKv12p0cHfu6sbOHaPsavTY9msd4Xuq8wAV2BMidO0'
RECONNECT_INTERVAL = 30
FORCE_CONNECT = 1

def log(message, init=0)
	#puts ("::#{Time.now}:: #{message}")
	$log_file.write("::#{Time.now}:: " + message + "\n")
	$log_file.flush
end

def end_response
  $response += "</ol></div>"
end

def start_response
  $response = "<div class='carousel' id='container'><ol>"
end

def request(method, params)
	begin
    call_uri = "http://search.twitter.com/#{method}?#{params}"
    response = REXML::Document.new(open(call_uri).read)
		return response
	rescue
		log("Request failed because: " + $!.to_s)
		return nil
	end
end

def get_tweets_for(tags)
  tweets=[]
  start_response
  response = request("search.atom", "q=#{CGI.escape(tags)}")
  if not response.nil?
    response.elements.each("*/entry/content") do |tweet|
      tweets << tweet.text
    end
  else 
    raise "Null response error"
  end
  if tweets.count > 0
    10.times do |i|
      $response += "<li>#{tweets[i]}</li>"
    end
  else
    $response += "<li>No tweets found for #{tags}</li>"
  end
  end_response
  puts $response
end
	
def encode(str)
  return str if str == "" || str == nil
  return str.gsub(/\'/, "\\\\'")
end

def daemonize()
	exit if fork                   # Parent exits, child continues.
	Process.setsid                 # Become session leader.
	exit if fork                   # Zap session leader. 
end

#Control start point
unless ARGV.length == 1
  puts "Dude, not the right number of arguments."
  puts "Usage: ruby twitter_tweet_puller.rb <tag> \n"
  exit
end


#daemonize()
$log_file = File.open("twitter_tweet_puller.log", "a+")
$response = ""
begin
  get_tweets_for(ARGV[0])
rescue
  log ($!.to_s)
  log "Twitter down! Twitter down!"
end
$log_file.close()
